import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart'
    hide RefreshIndicator, RefreshIndicatorState;
import 'package:flutter/widgets.dart';
import 'package:hzcloud_flt/feature/views/home.menus.view.dart';
import 'package:hzcloud_flt/feature/service_workbench.page.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class ServicePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _ServicePageState();
  }
}

class _ServicePageState extends State<ServicePage>
    with TickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  RefreshController _refreshController = RefreshController();
  TabController _tabController;
  ScrollController menuController = ScrollController();
  ScrollController _pullController = ScrollController();

  double _offsetX;
  Size indicatorSize;
  Size sIndicatorSize;
  final List<String> _tabValues = ['通知', '私信', '通讯录'];

  @override
  void initState() {
// TODO: implement initState
    _offsetX = 0;
    indicatorSize = Size(30, 4);
    sIndicatorSize = Size(15, 4);
    _refreshController.headerMode.addListener(() {
      print(_refreshController.position);
    });
    WidgetsBinding.instance.addPostFrameCallback((_) {
      setState(() {});
    });

    menuController.addListener(() {
      double maxScrollExtent = menuController.position.maxScrollExtent;
      double offsetX = menuController.offset > 0 ? menuController.offset : 0;
      double scrollLength = indicatorSize.width - sIndicatorSize.width;
      double progress = offsetX / maxScrollExtent > 1
          ? scrollLength
          : offsetX / maxScrollExtent * scrollLength;
      _offsetX = progress;
      setState(() {});
    });
    _tabController = TabController(length: _tabValues.length, vsync: this);
    super.initState();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    _refreshController.dispose();
    menuController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
// TODO: implement build
    return Scaffold(
      body: RefreshConfiguration(
        enableScrollWhenTwoLevel: true,
        maxOverScrollExtent: 100,
        child: SmartRefresher(
          controller: _refreshController,
          enableTwoLevel: true,
          enablePullDown: true,
          onLoading: () async {
            await Future.delayed(Duration(milliseconds: 2000));
            _refreshController.loadComplete();
          },
          onTwoLevel: (bool isOpen) {
            if (isOpen) {
              _refreshController.position.hold(() {});
              // Navigator.of(context)
              //     .push(MaterialPageRoute(
              //         builder: (c) => Scaffold(
              //               appBar: AppBar(),
              //               body: Text("二楼刷新"),
              //             )))
              //     .whenComplete(() {
              //   _refreshController.twoLevelComplete(
              //       duration: Duration(microseconds: 1));
              // });

              Navigator.push(
                context,
                PageRouteBuilder(pageBuilder: (BuildContext context,
                    Animation animation, Animation secondaryAnimation) {
                  return ServiceWorkBench();
                }, transitionsBuilder: (BuildContext context,
                    Animation<double> animation,
                    Animation<double> secondaryAnimation,
                    Widget child) {
                  return SlideTransition(
                    position: Tween(begin: Offset(0, -1), end: Offset(0, 0))
                        .animate(animation),
                    child: child,
                  );
                }),
              ).whenComplete(() => {
                    _refreshController.twoLevelComplete(
                        duration: Duration(microseconds: 1))
                  });
            }
          },
          onRefresh: () async {
            await Future.delayed(Duration(milliseconds: 2000));
            _refreshController.refreshCompleted();
          },
          header: ClassicHeader(
            textStyle: TextStyle(color: Colors.black),
            refreshingText: "加载中...",
            releaseText: "松开刷新",
            idleText: "下拉刷新",
            completeText: "刷新完成",
            canTwoLevelText: "松开更多功能",
          ),
          child: CustomScrollView(
            physics: ClampingScrollPhysics(),
            slivers: <Widget>[
              SliverToBoxAdapter(
                child: Padding(
                  padding: EdgeInsets.symmetric(
                    horizontal: 15,
                    vertical: 15,
                  ),
                  child: Row(
                    children: [
                      Expanded(
                        child: Text(
                          '服务',
                          style: TextStyle(
                            fontWeight: FontWeight.bold,
                            fontSize: 20,
                          ),
                        ),
                      ),
                      GestureDetector(
                        onTap: () {
                          print("===>");
                        },
                        child: Image.asset('assets/images/scan.png'),
                      )
                    ],
                  ),
                ),
              ),
              SliverToBoxAdapter(
                child: Container(
                  child: Scaffold(
                    body: Column(
                      children: <Widget>[
                        Container(
                          height: 80,
                          color: Colors.white,
                          child: GridView.count(
                            controller: menuController,
                            scrollDirection: Axis.horizontal,
                            crossAxisCount: 1,
                            children: List.generate(10, (i) {
                              return MenuItem(
                                onPress: () {
                                  _refreshController.requestTwoLevel();
                                },
                              );
                            }),
                          ),
                        ),
                        Container(
                          height: indicatorSize.height,
                          width: indicatorSize.width,
                          alignment: Alignment.centerLeft,
                          decoration: BoxDecoration(
                            color: Color(0xFFF2F2F2),
                            borderRadius: BorderRadius.circular(
                                indicatorSize.height / 2.0),
                          ),
                          child: Transform.translate(
                            offset: Offset(_offsetX, 0.0),
                            child: Container(
                              height: sIndicatorSize.height,
                              width: sIndicatorSize.width,
                              decoration: BoxDecoration(
                                color: Colors.blue,
                                borderRadius: BorderRadius.circular(
                                    indicatorSize.height / 2.0),
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                  height: 100.0,
                ),
              ),
              SliverToBoxAdapter(
                child: Column(
                  children: [
                    TabBar(
                      controller: _tabController,
                      indicatorSize: TabBarIndicatorSize.label,
                      indicatorWeight: 3,
                      labelColor: Colors.blueAccent,
                      labelStyle: TextStyle(fontSize: 15),
                      unselectedLabelColor: Colors.grey,
                      unselectedLabelStyle: TextStyle(fontSize: 15),
                      tabs: _tabValues
                          .map((String name) => Tab(text: name))
                          .toList(),
                      isScrollable: false,
                    ),
                  ],
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
